package com.cn.sc.scitc.cyol;


import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetJson {
    public String GetJson(String urls,JSONObject jsonObject) {
        StringBuffer sb=new StringBuffer();
        try {
            URL url = new URL(urls);// 创建url资源
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 建立http连接
            conn.setDoOutput(true);// 设置允许输出
            conn.setDoInput(true);// 设置允许输入
            conn.setUseCaches(false);// 设置不用缓存
            conn.setRequestMethod("POST");// 设置传递方式
            conn.setRequestProperty("Connection", "Keep-Alive");// 设置维持长连接
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");// 设置文件字符集:
            byte[] data = (jsonObject.toString()).getBytes();// 转换为字节数组
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));// 设置文件长度
            conn.setRequestProperty("contentType", "application/json");// 设置文件类型:
            conn.connect();// 开始连接请求
            OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
            out.write((jsonObject.toString()).getBytes());// 写入请求的字符串
            out.flush();
            out.close();
            System.out.println("青年大学习：" + conn.getResponseCode());
            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
                System.out.println("青年大学习：连接成功");
                InputStream in1 = conn.getInputStream();// 请求返回的数据
                try {
                    String readLine=new String();
                    BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
                    while((readLine=responseReader.readLine())!=null){
                        sb.append(readLine).append("");//Json 结束尾巴
//                        sb.append(readLine).append("/n");//原来的格式
                    }
                    responseReader.close();
                    System.out.println("青年大学习_Json获取:" + sb.toString());
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else {
                System.out.println("error++");
            }
        } catch (Exception e) {
        }
        return sb.toString();
    }
}
